import { useEffect, useState } from 'react'
import { Button, Col, Form, Input, Modal, Popover, Row, Select, Space, Table } from 'antd';
import { StationParkType, StationStatus, queryStationList } from './services'
import type { QueryStationListParams, Station } from './services'
import type { ColumnsType } from 'antd/es/table'
import { Access, history } from '@umijs/max'
import { useRequest } from 'ahooks'
import { PAGINATION_CONFIG } from '@/constants'
import usePageAccess from '@/components/usePageAccess'
import { enum2options } from '@/utils/enum2options'
import FeeModal from './components/FeeModal2'
import FeeModal2 from './components/FeeModal'
import type { FeeModalProps } from './components/FeeModal2'
import Ellipsis from '@/components/Ellipsis'
import DetailModal from './components/DetailModal'
import OrgSelect from '@/components/OrgSelect'
import { exportApply, exportStation, FromType } from '@/pages/order/chargeOrder/services';
import WhiteListModal from './components/WhiteListModal'
import TableActions from '@/components/TableActions'
import { jump2target } from '@/utils/common'
import { CheckCircleFilled } from '@ant-design/icons';
import ColumnDesc from '@/components/ColumnDesc';
import EvcsModal from '@/pages/station/stationList/components/EvcsModal';

const StationPage: React.FC<RoutePageProps> = (props) => {
  const access = usePageAccess()
  const [searchForm] = Form.useForm()
  const [searchParams, setSearchParams] = useState<QueryStationListParams>({
    pageNum: 1, pageSize: 10, ownerType: 1,
  });
  const stationList = useRequest(() => queryStationList(searchParams), {
    refreshDeps: [searchParams],
  })
  const [feeModalProps, setFeeModalProps] = useState<FeeModalProps>()
  const [feeModalProps2, setFeeModalProps2] = useState<FeeModalProps>()
  const [whiteListModalProps, setWhiteListModalProps] = useState<any>({open: false})
  const [detailId, setDetailId] = useState<string>()
  const expReq = useRequest(exportStation, {manual: true})
  const [evcsModalRecord, setEvcsModalRecord] = useState<Station>()
  const onFinish = (values: any) => {
    setSearchParams({
      ...searchParams,
      title: values.title,
      telephone:values.telephone,
      fromType: values.fromType,
      status: values.status,
      orgId: values.org?.id,
      pageNum: 1,
    })
  }

  const closeFeeModal = (refresh?: boolean) => {
    if (refresh) stationList.refresh()
    setFeeModalProps({open: false})
  }

  const closeFeeModal2 = () => {
    setFeeModalProps2({open: false})
  }
  const closeWhiteListModal = () => {
    setWhiteListModalProps({open: false})
  }

  const openFeeModal = (record: Station) => {
    setFeeModalProps({
      open: true,
      station: record,
    })
  }

  const openFeeModal2 = (record: Station) => {
    setFeeModalProps2({
      open: true,
      station: record,
    })
  }
  const closeEvcsModal = () => {
    setEvcsModalRecord(undefined)
  }
  const openEquipmentPage = (record: Station) => {
    jump2target(`/station/stubList?stationId=${record.id}&stationName=${record.stationName}`, {
      needRefresh: true
    })
  }

  const openEditPage = (title: string, type: string, id?: string) => {
    jump2target(`/station/shareStationList/edit?type=${type}&id=${id || ''}`, {needRefresh: true})
    sessionStorage.setItem('__/station/shareStationList/edit_title', title)
  }

  const openDetailModal = (record: Station) => {
    setDetailId(record.id)
  }

  const onDetailModalCancel = () => {
    setDetailId(undefined)
  }

  const exportExcel = () => {
    const formValues = searchForm.getFieldsValue()
    const _params = {
      ...searchParams,
      title: formValues.title,
      telephone: formValues.telephone,
      fromType: formValues.fromType,
      status: formValues.status,
      orgId: formValues.org?.id,
      pageNum: 1,
    }
    expReq.runAsync(_params)
      .then(res => {
        Modal.confirm({
          icon: <CheckCircleFilled style={{color: 'red'}} />,
          content: '导出申请成功，请前往导出记录查看文档。',
          onOk: () => {
            jump2target('/report/exportUrl')
          }
        })
      })
  }
  const openEvcsModal = (record: Station) => {
    setEvcsModalRecord(record)
  }

  const columns: ColumnsType<Station> = [
    {
      title: '场站名称',
      dataIndex: 'stationName'
    },
    {
      title: '私桩主信息',
      dataIndex: 'telephone',
      render: (_, record) => {
        const list = [
          {label: '昵称', value: record.nickname},
          {label: '手机号', value: record.telephone},
        ]
        return <ColumnDesc
          list={list}
        />
      }
    },

    {
      title: '场站来源',
      dataIndex: 'operatorId',
      render: val => val ? '互联互通' : '平台自建'
    },
    {
      title: '场站地址',
      dataIndex: 'address',
      render: val => val && <Popover content={val}>
        <Ellipsis>{val}</Ellipsis>
      </Popover>
    },
    {
      title: '经销商',
      dataIndex: 'orgName',
      width: 180,
      render: val => val || '--',
    },
    {
      title: '直流枪数',
      dataIndex: 'acNum',
      width: 90,
    },
    {
      title: '交流枪数',
      dataIndex: 'dcNum',
      width: 90,
    },
    {
      title: '额定功率(kW)',
      dataIndex: 'kw',
      width: 130,
    },
    {
      title: '停车费',
      dataIndex: 'parkType',
      width: 90,
      render: val => val && StationParkType[val]
    },
    {
      title: '状态',
      dataIndex: 'status',
      width: 90,
      render: val => StationStatus[val],
    },
    {
      title: '操作',
      key: 'operation',
      fixed: 'right',
      width: 200,
      render: (_, record) => {
        return (
          <TableActions>
            <a key='basicInfo' onClick={() => openDetailModal(record)}>详情</a>
            <a key='relevanceDevice' onClick={() => openEquipmentPage(record)}>设备列表</a>
            <Access accessible={!record.operatorId} fallback={
              <a key='electricPrice' onClick={() => openFeeModal2(record)}>电价</a>
            }>
              <a key='electricPrice' onClick={() => openFeeModal(record)}>电价</a>
            </Access>
            <a key='relevanceDevice' onClick={() => setWhiteListModalProps({open: true, id: record.id, title: record.stationName})}>白名单</a>
            <Access accessible={!record.operatorId}>
              <a key='edit' onClick={() => openEditPage('编辑场站', 'edit', record.id)}>编辑</a>
            </Access>
            <Access accessible={record.fromType === FromType.家苑设备}>
              <a key='edit' onClick={() => openEvcsModal(record)}>互联互通配置</a>
            </Access>
          </TableActions>
        )
      }
    },
  ]

  useEffect(() => {
    const refresh = () => {
      stationList.refresh()
    }
    window.addEventListener('refreshShareStationList', refresh)
    return () => {
      window.removeEventListener('refreshShareStationList', refresh)
    }
  }, [])

  useEffect(() => {
    if (props.params.orgId) {
      const formValues = {
        org: {
          id: props.params.orgId,
          name: props.params.orgName,
        }
      }
      searchForm.setFieldsValue(formValues)
      onFinish(formValues)
    }
  }, [props.params])
  
  return (
    <div className='container'>
      <div className="card search-card">
        <Access accessible={!!access.addStation || true}>
          <div className="toolbar">
            <Space>
              <Button type='primary' onClick={() => openEditPage('新建场站', 'edit')}>新建场站</Button>
            </Space>
          </div>
        </Access>
        <div className="form-area">
          <Form name='searchStationListForm' form={searchForm} onFinish={onFinish}>
            <Row gutter={[20, 20]}>
              <Col span={6}>
                <Form.Item label='用户手机号' name='telephone'>
                  <Input placeholder='请输入' />
                </Form.Item>
              </Col>
              <Col span={6}>
                <Form.Item label='场站名称' name='title'>
                  <Input placeholder='请输入' />
                </Form.Item>
              </Col>
              {/*<Col span={6}>*/}
              {/*  <Form.Item label='场站来源' name='fromType'>*/}
              {/*    <Select placeholder='请选择' options={enum2options(FromType)} allowClear />*/}
              {/*  </Form.Item>*/}
              {/*</Col>*/}
              <Col span={6}>
                <Form.Item label='状态' name='status'>
                  <Select placeholder='请选择' options={enum2options(StationStatus)} allowClear />
                </Form.Item>
              </Col>
              <Col span={6}>
                <Form.Item label='经销商ID' name='org'>
                  <OrgSelect allowClear inline />
                </Form.Item>
              </Col>
              <Col span={6}>
                <Space>
                  <Button type='primary' htmlType='submit' loading={stationList.loading}>筛选</Button>
                  <Button htmlType='reset'>重置</Button>
                  <Button onClick={exportExcel} loading={expReq.loading}>导出</Button>
                </Space>
              </Col>
            </Row>
          </Form>
        </div>
      </div>
      <div className="card content-card">
        <Table<Station>
          rowKey='id'
          loading={stationList.loading}
          dataSource={stationList.data?.data}
          columns={columns}
          scroll={{y: 700, x: 'max-content'}}
          pagination={{
            ...PAGINATION_CONFIG,
            current: searchParams.pageNum,
            pageSize: searchParams.pageSize,
            total: stationList.data?.totalCount || 0,
            onChange: (page, pageSize) => {
              setSearchParams({
                ...searchParams,
                pageNum: page === searchParams.pageNum ? 1 : page,
                pageSize,
              })
            }
          }}
        />
      </div>
      <FeeModal
        {...feeModalProps}
        onCancel={closeFeeModal}
      />
      <FeeModal2
        {...feeModalProps2}
        onCancel={closeFeeModal2}
      />
      <DetailModal
        id={detailId}
        onCancel={onDetailModalCancel}
      />
      <EvcsModal
        record={evcsModalRecord}
        onCancel={closeEvcsModal}
      />
      <WhiteListModal
        {...whiteListModalProps}
        onCancel={closeWhiteListModal}
      />
    </div>
  );
};

export default StationPage;
